Passed
Push — master ( 5a0225...e0b877 )
by Rafael S.
02:49
created

WaveFileCreator.fromExisting_   A

Complexity

Conditions 2

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 21
rs 9.95
c 0
b 0
f 0
cc 2
1
/*
2
 * Copyright (c) 2017-2019 Rafael da Silva Rocha.
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining
5
 * a copy of this software and associated documentation files (the
6
 * "Software"), to deal in the Software without restriction, including
7
 * without limitation the rights to use, copy, modify, merge, publish,
8
 * distribute, sublicense, and/or sell copies of the Software, and to
9
 * permit persons to whom the Software is furnished to do so, subject to
10
 * the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be
13
 * included in all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
 *
23
 */
24
25
/**
26
 * @fileoverview The WaveFileCreator class.
27
 * @see https://github.com/rochars/wavefile
28
 */
29
30
/** @module wavefile */
31
32
import WaveFileParser from './wavefile-parser';
33
import interleave from './interleave';
34
import dwChannelMask from './dw-channel-mask';
35
import validateNumChannels from './validate-num-channels'; 
36
import validateSampleRate from './validate-sample-rate';
37
import {packArrayTo, packTo, unpack} from 'byte-data';
38
39
/**
40
 * A class to read, write and create wav files.
41
 * @extends WaveFileParser
42
 */
43
export default class WaveFileCreator extends WaveFileParser {
44
45
  constructor() {
46
    super();
47
    /**
48
     * The bit depth code according to the samples.
49
     * @type {string}
50
     */
51
    this.bitDepth = '0';
52
    /**
53
     * @type {!Object}
54
     * @protected
55
     */
56
    this.dataType = {};
57
    /**
58
     * Audio formats.
59
     * Formats not listed here should be set to 65534,
60
     * the code for WAVE_FORMAT_EXTENSIBLE
61
     * @enum {number}
62
     * @protected
63
     */
64
    this.WAV_AUDIO_FORMATS = {
65
      '4': 17,
66
      '8': 1,
67
      '8a': 6,
68
      '8m': 7,
69
      '16': 1,
70
      '24': 1,
71
      '32': 1,
72
      '32f': 3,
73
      '64': 3
74
    };
75
  }
76
77
  /**
78
   * Set up the WaveFileCreator object based on the arguments passed.
79
   * Existing chunks are reset.
80
   * @param {number} numChannels The number of channels
81
   *    (Integer numbers: 1 for mono, 2 stereo and so on).
82
   * @param {number} sampleRate The sample rate.
83
   *    Integer numbers like 8000, 44100, 48000, 96000, 192000.
84
   * @param {string} bitDepthCode The audio bit depth code.
85
   *    One of '4', '8', '8a', '8m', '16', '24', '32', '32f', '64'
86
   *    or any value between '8' and '32' (like '12').
87
   * @param {!Array<number>|!Array<!Array<number>>|!TypedArray} samples
88
   *    The samples. Must be in the correct range according to the bit depth.
89
   * @param {?Object} options Optional. Used to force the container
90
   *    as RIFX with {'container': 'RIFX'}
91
   * @throws {Error} If any argument does not meet the criteria.
92
   */
93
  fromScratch(numChannels, sampleRate, bitDepthCode, samples, options={}) {
94
    // reset all chunks
95
    this.clearHeaders();
96
    this.newWavFile_(numChannels, sampleRate, bitDepthCode, samples, options);
97
  }
98
99
  /**
100
   * Set up the WaveFileCreator object based on the arguments passed.
101
   * @param {number} numChannels The number of channels
102
   *    (Integer numbers: 1 for mono, 2 stereo and so on).
103
   * @param {number} sampleRate The sample rate.
104
   *    Integer numbers like 8000, 44100, 48000, 96000, 192000.
105
   * @param {string} bitDepthCode The audio bit depth code.
106
   *    One of '4', '8', '8a', '8m', '16', '24', '32', '32f', '64'
107
   *    or any value between '8' and '32' (like '12').
108
   * @param {!Array<number>|!Array<!Array<number>>|!TypedArray} samples
109
   *    The samples. Must be in the correct range according to the bit depth.
110
   * @param {?Object} options Optional. Used to force the container
111
   *    as RIFX with {'container': 'RIFX'}
112
   * @throws {Error} If any argument does not meet the criteria.
113
   * @private
114
   */
115
  newWavFile_(numChannels, sampleRate, bitDepthCode, samples, options={}) {
116
    if (!options.container) {
117
      options.container = 'RIFF';
118
    }
119
    this.container = options.container;
120
    this.bitDepth = bitDepthCode;
121
    samples = interleave(samples);
122
    this.updateDataType_();
123
    /** @type {number} */
124
    let numBytes = this.dataType.bits / 8;
125
    this.data.samples = new Uint8Array(samples.length * numBytes);
126
    packArrayTo(samples, this.dataType, this.data.samples);
127
    this.makeWavHeader_(
128
      bitDepthCode, numChannels, sampleRate,
129
      numBytes, this.data.samples.length, options);
130
    this.data.chunkId = 'data';
131
    this.data.chunkSize = this.data.samples.length;
132
    this.validateWavHeader_();
133
  }
134
135
  /**
136
   * Set up the WaveFileParser object from a byte buffer.
137
   * @param {!Uint8Array} wavBuffer The buffer.
138
   * @param {boolean=} samples True if the samples should be loaded.
139
   * @throws {Error} If container is not RIFF, RIFX or RF64.
140
   * @throws {Error} If format is not WAVE.
141
   * @throws {Error} If no 'fmt ' chunk is found.
142
   * @throws {Error} If no 'data' chunk is found.
143
   */
144
  fromBuffer(wavBuffer, samples=true) {
145
    super.fromBuffer(wavBuffer, samples);
146
    this.bitDepthFromFmt_();
147
    this.updateDataType_();
148
  }
149
150
  /**
151
   * Return a byte buffer representig the WaveFileParser object as a .wav file.
152
   * The return value of this method can be written straight to disk.
153
   * @return {!Uint8Array} A wav file.
154
   * @throws {Error} If bit depth is invalid.
155
   * @throws {Error} If the number of channels is invalid.
156
   * @throws {Error} If the sample rate is invalid.
157
   */
158
  toBuffer() {
159
    this.validateWavHeader_();
160
    return super.toBuffer();
161
  }
162
163
  /**
164
   * Return the sample at a given index.
165
   * @param {number} index The sample index.
166
   * @return {number} The sample.
167
   * @throws {Error} If the sample index is off range.
168
   */
169
  getSample(index) {
170
    index = index * (this.dataType.bits / 8);
171
    if (index + this.dataType.bits / 8 > this.data.samples.length) {
172
      throw new Error('Range error');
173
    }
174
    return unpack(
175
      this.data.samples.slice(index, index + this.dataType.bits / 8),
176
      this.dataType);
177
  }
178
179
  /**
180
   * Set the sample at a given index.
181
   * @param {number} index The sample index.
182
   * @param {number} sample The sample.
183
   * @throws {Error} If the sample index is off range.
184
   */
185
  setSample(index, sample) {
186
    index = index * (this.dataType.bits / 8);
187
    if (index + this.dataType.bits / 8 > this.data.samples.length) {
188
      throw new Error('Range error');
189
    }
190
    packTo(sample, this.dataType, this.data.samples, index);
191
  }
192
193
  /**
194
   * Define the header of a wav file.
195
   * @param {string} bitDepthCode The audio bit depth
196
   * @param {number} numChannels The number of channels
197
   * @param {number} sampleRate The sample rate.
198
   * @param {number} numBytes The number of bytes each sample use.
199
   * @param {number} samplesLength The length of the samples in bytes.
200
   * @param {!Object} options The extra options, like container defintion.
201
   * @private
202
   */
203
  makeWavHeader_(
204
    bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options) {
205
    if (bitDepthCode == '4') {
206
      this.createADPCMHeader_(
207
        bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options);
208
209
    } else if (bitDepthCode == '8a' || bitDepthCode == '8m') {
210
      this.createALawMulawHeader_(
211
        bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options);
212
213
    } else if(Object.keys(this.WAV_AUDIO_FORMATS).indexOf(bitDepthCode) == -1 ||
214
        numChannels > 2) {
215
      this.createExtensibleHeader_(
216
        bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options);
217
218
    } else {
219
      this.createPCMHeader_(
220
        bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options);      
221
    }
222
  }
223
224
  /**
225
   * Create the header of a linear PCM wave file.
226
   * @param {string} bitDepthCode The audio bit depth
227
   * @param {number} numChannels The number of channels
228
   * @param {number} sampleRate The sample rate.
229
   * @param {number} numBytes The number of bytes each sample use.
230
   * @param {number} samplesLength The length of the samples in bytes.
231
   * @param {!Object} options The extra options, like container defintion.
232
   * @private
233
   */
234
  createPCMHeader_(
235
    bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options) {
236
    this.container = options.container;
237
    this.chunkSize = 36 + samplesLength;
238
    this.format = 'WAVE';
239
    this.bitDepth = bitDepthCode;
240
    this.fmt = {
241
      chunkId: 'fmt ',
242
      chunkSize: 16,
243
      audioFormat: this.WAV_AUDIO_FORMATS[bitDepthCode] || 65534,
244
      numChannels: numChannels,
245
      sampleRate: sampleRate,
246
      byteRate: (numChannels * numBytes) * sampleRate,
247
      blockAlign: numChannels * numBytes,
248
      bitsPerSample: parseInt(bitDepthCode, 10),
249
      cbSize: 0,
250
      validBitsPerSample: 0,
251
      dwChannelMask: 0,
252
      subformat: []
253
    };
254
  }
255
256
  /**
257
   * Create the header of a ADPCM wave file.
258
   * @param {string} bitDepthCode The audio bit depth
259
   * @param {number} numChannels The number of channels
260
   * @param {number} sampleRate The sample rate.
261
   * @param {number} numBytes The number of bytes each sample use.
262
   * @param {number} samplesLength The length of the samples in bytes.
263
   * @param {!Object} options The extra options, like container defintion.
264
   * @private
265
   */
266
  createADPCMHeader_(
267
    bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options) {
268
    this.createPCMHeader_(
269
      bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options);
270
    this.chunkSize = 40 + samplesLength;
271
    this.fmt.chunkSize = 20;
272
    this.fmt.byteRate = 4055;
273
    this.fmt.blockAlign = 256;
274
    this.fmt.bitsPerSample = 4;
275
    this.fmt.cbSize = 2;
276
    this.fmt.validBitsPerSample = 505;
277
    this.fact = {
278
      chunkId: 'fact',
279
      chunkSize: 4,
280
      dwSampleLength: samplesLength * 2
281
    };
282
  }
283
284
  /**
285
   * Create the header of WAVE_FORMAT_EXTENSIBLE file.
286
   * @param {string} bitDepthCode The audio bit depth
287
   * @param {number} numChannels The number of channels
288
   * @param {number} sampleRate The sample rate.
289
   * @param {number} numBytes The number of bytes each sample use.
290
   * @param {number} samplesLength The length of the samples in bytes.
291
   * @param {!Object} options The extra options, like container defintion.
292
   * @private
293
   */
294
  createExtensibleHeader_(
295
      bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options) {
296
    this.createPCMHeader_(
297
      bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options);
298
    this.chunkSize = 36 + 24 + samplesLength;
299
    this.fmt.chunkSize = 40;
300
    this.fmt.bitsPerSample = ((parseInt(bitDepthCode, 10) - 1) | 7) + 1;
301
    this.fmt.cbSize = 22;
302
    this.fmt.validBitsPerSample = parseInt(bitDepthCode, 10);
303
    this.fmt.dwChannelMask = dwChannelMask(numChannels);
304
    // subformat 128-bit GUID as 4 32-bit values
305
    // only supports uncompressed integer PCM samples
306
    this.fmt.subformat = [1, 1048576, 2852126848, 1905997824];
307
  }
308
309
  /**
310
   * Create the header of mu-Law and A-Law wave files.
311
   * @param {string} bitDepthCode The audio bit depth
312
   * @param {number} numChannels The number of channels
313
   * @param {number} sampleRate The sample rate.
314
   * @param {number} numBytes The number of bytes each sample use.
315
   * @param {number} samplesLength The length of the samples in bytes.
316
   * @param {!Object} options The extra options, like container defintion.
317
   * @private
318
   */
319
  createALawMulawHeader_(
320
      bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options) {
321
    this.createPCMHeader_(
322
      bitDepthCode, numChannels, sampleRate, numBytes, samplesLength, options);
323
    this.chunkSize = 40 + samplesLength;
324
    this.fmt.chunkSize = 20;
325
    this.fmt.cbSize = 2;
326
    this.fmt.validBitsPerSample = 8;
327
    this.fact = {
328
      chunkId: 'fact',
329
      chunkSize: 4,
330
      dwSampleLength: samplesLength
331
    };
332
  }
333
334
  /**
335
   * Set the string code of the bit depth based on the 'fmt ' chunk.
336
   * @private
337
   */
338
  bitDepthFromFmt_() {
339
    if (this.fmt.audioFormat === 3 && this.fmt.bitsPerSample === 32) {
340
      this.bitDepth = '32f';
341
    } else if (this.fmt.audioFormat === 6) {
342
      this.bitDepth = '8a';
343
    } else if (this.fmt.audioFormat === 7) {
344
      this.bitDepth = '8m';
345
    } else {
346
      this.bitDepth = this.fmt.bitsPerSample.toString();
347
    }
348
  }
349
350
  /**
351
   * Validate the bit depth.
352
   * @return {boolean} True is the bit depth is valid.
353
   * @throws {Error} If bit depth is invalid.
354
   * @private
355
   */
356
  validateBitDepth_() {
357
    if (!this.WAV_AUDIO_FORMATS[this.bitDepth]) {
358
      if (parseInt(this.bitDepth, 10) > 8 &&
359
          parseInt(this.bitDepth, 10) < 54) {
360
        return true;
361
      }
362
      throw new Error('Invalid bit depth.');
363
    }
364
    return true;
365
  }
366
367
  /**
368
   * Update the type definition used to read and write the samples.
369
   * @private
370
   */
371
  updateDataType_() {
372
    this.dataType = {
373
      bits: ((parseInt(this.bitDepth, 10) - 1) | 7) + 1,
374
      fp: this.bitDepth == '32f' || this.bitDepth == '64',
375
      signed: this.bitDepth != '8',
376
      be: this.container == 'RIFX'
377
    };
378
    if (['4', '8a', '8m'].indexOf(this.bitDepth) > -1 ) {
379
      this.dataType.bits = 8;
380
      this.dataType.signed = false;
381
    }
382
  }
383
384
  /**
385
   * Validate the header of the file.
386
   * @throws {Error} If bit depth is invalid.
387
   * @throws {Error} If the number of channels is invalid.
388
   * @throws {Error} If the sample rate is invalid.
389
   * @ignore
390
   * @private
391
   */
392
  validateWavHeader_() {
393
    this.validateBitDepth_();
394
    if (!validateNumChannels(this.fmt.numChannels, this.fmt.bitsPerSample)) {
395
      throw new Error('Invalid number of channels.');
396
    }
397
    if (!validateSampleRate(
398
        this.fmt.numChannels, this.fmt.bitsPerSample, this.fmt.sampleRate)) {
399
      throw new Error('Invalid sample rate.');
400
    }
401
  }
402
}
403